package nl.hva.web.mvcwebapp.controllers;

import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.*;
import javax.servlet.http.*;
import nl.hva.web.mvcwebapp.doa.CourseDAO;
import nl.hva.web.mvcwebapp.models.ForumThread;
import nl.hva.web.mvcwebapp.models.ForumTopic;
import nl.hva.web.mvcwebapp.models.User;
import nl.hva.web.mvcwebapp.doa.ForumDAO;
import nl.hva.web.mvcwebapp.doa.UserDAO;
import nl.hva.web.mvcwebapp.models.Course;
import nl.hva.web.mvcwebapp.models.ForumComment;
import nl.hva.web.mvcwebapp.service.HibernateUtil;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class ForumController extends HttpServlet {

    private String address = "forumThread/forum.jsp";

    /*
     * HTTP GET request
     */
    public ArrayList getPaths() {
        ArrayList paths = new ArrayList();
        paths.add(0, "/forum");
        paths.add(1, "/forum/topic_add");
        paths.add(2, "/forum/topic_view");
        paths.add(3, "/forum/thread_add");
        paths.add(4, "/forum/thread_view");
        paths.add(5, "/forum/delete_comment");
        paths.add(6, "/forum/edit_comment");
        return paths;
    }

    public ArrayList getPathsJSP() {
        ArrayList paths_jsp = new ArrayList();
        paths_jsp.add(0, "/forumThread/forum.jsp");
        paths_jsp.add(1, "/forumThread/topic_add.jsp");
        paths_jsp.add(2, "/forumThread/topic_view.jsp");
        paths_jsp.add(3, "/forumThread/thread_add.jsp");
        paths_jsp.add(4, "/forumThread/thread_view.jsp");
        paths_jsp.add(5, "/forumThread/thread_view.jsp");
        paths_jsp.add(6, "/forumThread/comment_edit.jsp");
        return paths_jsp;
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {

        ArrayList paths = getPaths();
        ArrayList paths_jsp = getPathsJSP();
        String path = request.getServletPath();
        boolean redirect = true;

        for (int i = 0; i < paths.size(); i++) {
            System.out.println(i);
            try {
                if (path.equals(paths.get(i).toString())
                        || path.substring(0, path.toString().length() - 1).equals(paths.get(i).toString())) {
                    address = paths_jsp.get(i).toString();
                    //Forums
                    if (i == 0) {

                        List<ForumTopic> forums = ForumDAO.getAllForums();
                        request.setAttribute("pageTitle", "Forum");
                        request.setAttribute("forumsUitSessie", forums);
                        request.setAttribute("aantalForums", forums.size());

                        List<ForumThread> threads = ForumDAO.getAllThreads();

                        request.setAttribute("threadsUitSessie", threads);
                        request.setAttribute("aantalThreads", threads.size());



                    } //topic add
                    else if (i == 1) {
                        int id = Integer.parseInt(request.getParameter("id"));
                        ForumTopic forum = ForumDAO.getForum(id);
                        request.setAttribute("forum", forum);
                        request.setAttribute("pageTitle", "New forum");

                    } // topic view
                    else if (i == 2) {
                        //view topic: id=?
                        if (request.getParameter("topic_id") != null && !request.getParameter("topic_id").isEmpty()) {
                            int topic_id = Integer.parseInt(request.getParameter("topic_id"));

                            ForumTopic topic = ForumDAO.getForum(topic_id);
                            String topicName = "View topic: " + topic.getForumTopicName();
                            String topicBody = topic.getForumtopicbody();

                            request.setAttribute("pageTitle", topicName);
                            request.setAttribute("parentTopic", topic_id);
                            request.setAttribute("topicBody", topicBody);

                            List<ForumTopic> topics = ForumDAO.getChildTopics(request.getParameter("topic_id"));
                            request.setAttribute("topics", topics);

                            List<ForumThread> threads = ForumDAO.getChildThreads(request.getParameter("topic_id"));
                            request.setAttribute("threads", threads);
                        } //view topic of the course: course_id=?
                        else if (request.getParameter("courseid") != null && !request.getParameter("courseid").isEmpty()) {
                            int course_id = Integer.parseInt(request.getParameter("courseid"));
                            int courseTopicId = ForumDAO.getCourseForum(course_id);
                            Course mycourse = CourseDAO.getCourse(course_id);
                            request.setAttribute("pageTitle", "View forum of the course " + mycourse.getCoursetitle());
                            ForumTopic topic = ForumDAO.getForum(courseTopicId);
                            String topicBody = topic.getForumtopicbody();
                            request.setAttribute("parentTopic", courseTopicId);
                            request.setAttribute("topicBody", topicBody);
                            List<ForumTopic> topics = ForumDAO.getChildTopics(Integer.toString(courseTopicId));
                            request.setAttribute("topics", topics);
                            List<ForumThread> threads = ForumDAO.getChildThreads(Integer.toString(courseTopicId));
                            request.setAttribute("threads", threads);

                        }

                    } //thread view
                    else if (i == 4) {
                        int thread_id = Integer.parseInt(request.getParameter("thread_id"));

                        ForumThread thread = ForumDAO.getThread(thread_id);
                        String threadName = "View thread: " + thread.getForumThreadName();
                        String threadBody = thread.getForumThreadBody();

                        request.setAttribute("pageTitle", threadName);
                        request.setAttribute("thread", thread);
                        request.setAttribute("threadBody", threadBody);
                        request.setAttribute("currentUserId", UserController.userAccountId); //set the id of the logged in user

                        List<ForumComment> comments = ForumDAO.getComments(thread_id);
                        request.setAttribute("comments", comments);
                        request.setAttribute("commentsSize", comments.size());
                    } //delete comment
                    else if (i == 5) {
                        int comment_id = Integer.parseInt(request.getParameter("comment_id"));
                        int thread_id = Integer.parseInt(request.getParameter("thread_id"));
                        ForumDAO.deleteComment(comment_id);
                        redirect = false;
                        response.sendRedirect("../forum/thread_view?thread_id=" + thread_id);
                    } else if (i == 6) {
                        int comment_id = Integer.parseInt(request.getParameter("comment_id"));
                        int thread_id = Integer.parseInt(request.getParameter("thread_id"));
                        ForumComment comment = ForumDAO.getComment(comment_id);
                        ForumThread thread = ForumDAO.getThread(thread_id);
                        request.setAttribute("comment", comment);
                        request.setAttribute("pageTitle", "Edit comment");
                        request.setAttribute("threadName", thread.getForumThreadName());
                        
                    }
                }
            } catch (Exception E) {
            }
        }
        if (redirect) {
            request.setAttribute("path", path);
            RequestDispatcher dispatcher = request.getRequestDispatcher(address);
            dispatcher.forward(request, response);
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        ArrayList paths = getPaths();
        ArrayList paths_jsp = getPathsJSP();

        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();
        String path = request.getServletPath();

        for (int i = 0; i < paths.size(); i++) {
            try {

                if (path.equals(paths.get(i).toString())
                        || path.substring(0, path.toString().length() - 1).equals(paths.get(i).toString())) {
                    address = paths_jsp.get(i).toString();
                    System.out.println("i in the post is: " + i);
                    if (i == 0) {
                        response.sendRedirect("../forum");
                    } // ---------------- /forum/new + /forum/edit --------------------
                    else if (i == 1) {
                        //new child to the parent
                        if (request.getParameter("parenttopic_id") != null && !request.getParameter("parenttopic_id").isEmpty()) {
                            int parent_id = Integer.parseInt(request.getParameter("parenttopic_id"));

                            ForumTopic newForum = getForumFromRequest(request, new ForumTopic());
                            ForumDAO.insertForum(newForum, parent_id);

                            response.sendRedirect("../forum/topic_view?topic_id=" + parent_id);
                        } //edit  - DOESN"T WORK YET
                        /*      else if (request.getParameter("id") != null && !request.getParameter("id").isEmpty()) {
                         int id = Integer.parseInt(request.getParameter("id"));
                         ForumTopic forum = (ForumTopic) session.get(ForumTopic.class, id);
                         ForumTopic forum_update = getForumFromRequest(request, forum);
                         session.update(forum_update);
                         }*/ else {
                            //new
                            ForumDAO.newForum(getForumFromRequest(request, new ForumTopic()));
                            response.sendRedirect("../forum");
                        }

                    } //---------------- /forum/thread_add --------------------------
                    else if (i == 3) {
                        //add thread to the parent topic
                        if (request.getParameter("parenttopic_id") != null && !request.getParameter("parenttopic_id").isEmpty()) {
                            int parenttopic_id = Integer.parseInt(request.getParameter("parenttopic_id"));
                            ForumThread newThread = getThreadFromRequest(request, new ForumThread());
                            ForumDAO.insertThread(newThread, parenttopic_id);
                            response.sendRedirect("../forum/topic_view?topic_id=" + parenttopic_id);
                        } else {
                            //add thread without parent
                            ForumDAO.newThread(getThreadFromRequest(request, new ForumThread()));
                            response.sendRedirect("../forum");
                        }
                    } //add comment to this thread
                    else if (i == 4) {
                        int thread_id = Integer.parseInt(request.getParameter("thread_id"));
                        ForumComment newComment = getCommentFromRequest(request, new ForumComment());
                        ForumDAO.insertComment(newComment, thread_id);
                        response.sendRedirect("../forum/thread_view?thread_id=" + thread_id);
                    } //edit comment
                    else if(i == 6){
                        int thread_id = Integer.parseInt(request.getParameter("thread_id"));
                        int comment_id = Integer.parseInt(request.getParameter("comment_id"));
                        //ForumComment comment = ForumDAO.getComment(comment_id);
                        //comment.setForumcomment_body(request.getParameter("commentbody"));
                        //ForumDAO.updateComment(comment);
                        String commentBody = request.getParameter("commentbody");
                        ForumDAO.updateComment(comment_id, commentBody);
                        
                        response.sendRedirect("../forum/thread_view?thread_id=" + thread_id);
                    }

                }

            } catch (Exception E) {
            }
        }

    }

    public ForumTopic getForumFromRequest(HttpServletRequest request, ForumTopic forum) {
        /*if (request.getParameter("parenttopic_id") != null && !request.getParameter("parenttopic_id").isEmpty()) { //which means that it is a child of the parent topic   
         forum.setParentTopic(ForumDAO.getForum(Integer.parseInt(request.getParameter("parenttopic_id"))));
         }*/
        if (request.getParameter("forumtopicname") != null) {
            forum.setForumTopicName(request.getParameter("forumtopicname"));
        }
        if (request.getParameter("forumtopicbody") != null) {
            forum.setForumtopicbody(request.getParameter("forumtopicbody"));
        }
        if (request.getParameter("sticky") != null) {
            forum.setSticky(Integer.parseInt(request.getParameter("sticky")));
        }

        return forum;
    }

    public ForumThread getThreadFromRequest(HttpServletRequest request, ForumThread thread) {
        if (request.getParameter("forumThreadId") != null && !request.getParameter("forumThreadId").isEmpty()) {
            thread.setForumThreadId(Integer.parseInt(request.getParameter("forumThreadId")));
        }

        if (request.getParameter("forumthreadname") != null) {
            thread.setForumThreadName(request.getParameter("forumthreadname"));
        }
        if (request.getParameter("forumthreadbody") != null) {
            thread.setForumThreadBody(request.getParameter("forumthreadbody"));
        }
        return thread;
    }

    public ForumComment getCommentFromRequest(HttpServletRequest request, ForumComment comment) {
        if (request.getParameter("commentbody") != null && !request.getParameter("commentbody").isEmpty()) {
            comment.setForumcomment_body(request.getParameter("commentbody"));
        }

        int userId = UserController.userAccountId;
        comment.setUser(UserDAO.getUser(userId));

        DateFormat df = new SimpleDateFormat("dd MMMM yyyy HH:mm:ss");
        Date today = Calendar.getInstance().getTime();        
        String reportDate = df.format(today);
        System.out.println("DATE TESTING: "+reportDate);
        //Date date = new Date();
        comment.setTimestampp(reportDate);

        return comment;
    }
}
